package test.struts.utils;

import java.util.*;
import javax.servlet.http.HttpServletRequest;

public class ULink {
	private String href;
	private Hashtable params;
	private HttpServletRequest request;

	public ULink(String href, HttpServletRequest request) {
		this.request = request;
		this.href = href;
		params = new Hashtable();
	}

	public void addParameter(String paramName, Object paramValue) {
		if (paramValue == null) {
			paramValue = "";
		}

		params.put(paramName, paramValue);
	}

	public String toString() {
		String pName;
		String pValue;
		StringBuffer sb = new StringBuffer();

		sb.append(_obtenerRaiz(request));

		sb.append(href);
		if (params.size() > 0) {
			sb.append("?");
		}

		int i = 0;
		for (Enumeration e = params.keys(); e.hasMoreElements();) {
			pName = (String) e.nextElement();
			pValue = params.get(pName).toString();
			sb.append(pName + "=" + pValue);
			if (i++ < params.size() - 1) {
				sb.append("&");
			}
		}
		return sb.toString();
	}

	private String _obtenerRaiz(HttpServletRequest req) {
		StringBuffer sb = req.getRequestURL();
		String url = sb.toString();
		String cp = req.getContextPath();
		int pos = url.indexOf(cp);
		String s1 = url.substring(0, pos);
		String s2 = s1 + cp;
		return s2;
	}
}